package com.englisheveryday.db;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.englisheveryday.constants.Constants;
import com.englisheveryday.utils.L;
import com.englisheveryday.utils.LocaleUtil;
import com.englisheveryday.utils.StringUtil;
import com.englisheveryday.utils.UUIDGenerator;
import com.englisheveryday.vo.ArticleVO;

/**
 * <pre>
 *    
 * </pre>
 * @author 马永华
 * @date 2012-9-8 下午10:26:50
 * @version 1.1
 */

public class ArticleDAO  {

	private DBHelper  dbHelper;
	private List<String> errorIdList;
	
	public ArticleDAO(Context context){
		dbHelper = new DBHelper(context, "/data/data/com.englisheveryday/englishdata.db");
		errorIdList = new ArrayList<String>();
	}
	
	
	//获得所有的每日口语信息
	public List<ArticleVO> getAll(String page,String count){
		List<ArticleVO> articleList = new  ArrayList<ArticleVO>();
		SQLiteDatabase db = null;
		Cursor cursor = null;
		try{
	    db = dbHelper.getWritableDatabase();
	    cursor = db.rawQuery(Constants.ARTICLE_SELECT_PAGE_SQL,new String[]{page,count});
	    L.d(cursor.getCount()+"");
		while(cursor.moveToNext()){
			ArticleVO vo = new ArticleVO();
			vo.setTitle(StringUtil.replaceNull(cursor.getString(cursor.getColumnIndex("title"))));
			vo.setEnglishText(StringUtil.replaceNull(cursor.getString(cursor.getColumnIndex("englishtext"))));
			vo.setCategory(StringUtil.replaceNull(cursor.getString(cursor.getColumnIndex("categoryname"))));
			vo.setMark(StringUtil.replaceNull(cursor.getString(cursor.getColumnIndex("mark"))));
			vo.setAudio(StringUtil.replaceNull(cursor.getString(cursor.getColumnIndex("audio"))));
			vo.setCreatetime(cursor.getLong(cursor.getColumnIndex("createtime")));
			vo.setId(cursor.getString(cursor.getColumnIndex("id")));
			L.d(vo.getCategory());
			articleList.add(vo);
		}
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			if(db!=null&&db.isOpen())
				db.close();
			if(cursor!=null)
				cursor.close();
		}
		return articleList;
	}
	
	//保存每日口语信息
	public void insert(ArticleVO vo,SQLiteDatabase db){
		String id = "";
		try{
		ContentValues cv = new ContentValues();
		cv.put("title", vo.getTitle());
		cv.put("englishtext", vo.getEnglishText());
		cv.put("category", vo.getCategory());
		cv.put("explain", vo.getExplain());
		cv.put("mark", vo.getMark());
		cv.put("audio", vo.getAudio());
		cv.put("createtime",vo.getCreatetime());
		cv.put("id",vo.getId());
		id = vo.getId();
		if(findbyid(vo.getId(),db)>0){
			L.d("已经存在了");
			return;
		}
		long l = db.insert("article", null, cv);
		L.d("插入:"+l);
		}catch(Exception e){
			e.printStackTrace();
			errorIdList.add(id);
		}
	}
	
	//更新每日口语信息
	public void update(ArticleVO vo,SQLiteDatabase db){
		String id = "";
		try{
			ContentValues cv = new ContentValues();
			cv.put("title", vo.getTitle());
			cv.put("englishtext", vo.getEnglishText());
			cv.put("category", vo.getCategory());
			cv.put("explain", vo.getExplain());
			cv.put("mark", vo.getMark());
			cv.put("audio", vo.getAudio());
			id = vo.getId();
			if(findbyid(vo.getId(),db)==0){
				L.d("不存在");
				return;
			}
			long l = db.update("article", cv,"id=?", new String[]{vo.getId()});
			L.d("更新："+l);
		}catch(Exception e){
			e.printStackTrace();
			errorIdList.add(id);
		}
		
	}
	
	//批量更新
	public void sync(List<ArticleVO> list,long nextAnchor){
		SQLiteDatabase db = null;
		errorIdList.clear();
		try {
			db = dbHelper.getWritableDatabase();
			for(ArticleVO vo : list){
				if(vo!=null&&"A".equals(vo.getType())){
					insert(vo,db);
				}else if(vo!=null&&"D".equals(vo.getType())){
					delete(vo.getId(),db);
				}else if(vo!=null&&"U".equals(vo.getType())){
					update(vo,db);
				}
			}
			L.d("失败："+errorIdList.size());
			//更新时间戳
			updateAnchor(nextAnchor,db);
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			if(db!=null&&db.isOpen())
				db.close();
		}
	}
	
	//删除
	public int delete(String id,SQLiteDatabase db){
		int count = 0;
		try{
			count = db.delete("article", "id=?",new String[]{id});
		}catch(Exception e){
			e.printStackTrace();
			errorIdList.add(id);
		}
		return count;
	}
	
	public int delete(String id){
		int count = 0;
		SQLiteDatabase db = null;
		try{
			db = dbHelper.getWritableDatabase();
			count = db.delete("article", "id=?",new String[]{id});
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			if(db!=null&&db.isOpen())
				db.close();
		}
		return count;
	}
	
	//收藏
	public int mark(String id){
		SQLiteDatabase db = null;
		  int count = 0;
		  try{
			  db = dbHelper.getWritableDatabase();
			 ContentValues cv = new ContentValues();
			 cv.put("mark", "1");
			count =  db.update("article", cv, "id=?", new String[]{id});
		  }catch(Exception e){
			  e.printStackTrace();
		  }finally {
			  if(db!=null&&db.isOpen())
					db.close();
		  }
		  return count;
	}
	
	//取消收藏
	public int unMark(String id){
		SQLiteDatabase db = null;
		  int count = 0;
		  try{
			  db = dbHelper.getWritableDatabase();
			 ContentValues cv = new ContentValues();
			 cv.put("mark", "0");
			count =  db.update("article", cv, "id=?", new String[]{id});
		  }catch(Exception e){
		    e.printStackTrace();
		  }finally {
			  if(db!=null&&db.isOpen())
					db.close();
		  }
		  return count;
	}
	
	//是否收藏
	public boolean isMark(String id){
		SQLiteDatabase db = null;
		int count = 0;
		try{
			db = dbHelper.getWritableDatabase();
			Cursor cursor = db.rawQuery(Constants.ARTICLE_IS_MARK, new String[]{id});
			count = cursor.getCount();
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			if(db!=null&&db.isOpen())
				db.close();
		}
		L.d(""+(count>0));
		return count>0;
	}
	
	//查询是否存在
	public int findbyid(String id,SQLiteDatabase db){
		Cursor cursor = db.rawQuery(Constants.ARTICLE_SELECT_BY_ID, new String[]{id});
		int count = cursor.getCount();
		return count;
	}
	
	
	//查询上次更新的时间戳
	public long queryAnchor(){
		SQLiteDatabase db = null;
		long anchor = 0;
		try{
			db = dbHelper.getWritableDatabase();
			Cursor cursor = db.rawQuery("select anchor  from updatelog where type=?",new String[]{Constants.ANCHOR_ARTICLE});
			if(cursor!=null&&cursor.getCount()>0){
				cursor.moveToFirst();
				anchor = cursor.getLong(cursor.getColumnIndex("anchor"));
				L.d("an:"+anchor);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			if(db!=null&&db.isOpen())
				db.close();
		}
		return anchor;
	}
	
	
	//更新本次时间戳
	public int updateAnchor(long anchor,SQLiteDatabase db){
		int count  = 0;
		if(anchor==0)
			return count;
		try{
			ContentValues cv = new ContentValues();
			cv.put("anchor", anchor);
			count = db.update("updatelog", cv, "type=?",new String[]{Constants.ANCHOR_ARTICLE});
			L.d("anchor"+count);
		}catch(Exception e){
			e.printStackTrace();
		}
		return count;
	}
}

